import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import pandas as pd
from modules.Demographics.src.module1 import china_population_generator

# 1. 生成中国虚拟人群并保存为csv
china_population_generator.generate_china_population(
    n=100,
    min_age=20,
    max_age=80,
    female_ratio=0.5,
    age_dist='Uniform',
    output_csv='china_population.csv'
)

# 2. 读取人口学csv
pop_df = pd.read_csv('china_population.csv')

# 3. 传递到后续模块
from modules.Kidney.Kidney import generate_kidney_parameters_from_df, generate_kidney_transporters_from_df
from modules.Liver.liver_calculator import LiverParametersCalculator
from modules.Liver.liver_enzymes_transporters import generate_liver_enzymes_transporters_from_df
from modules.GI.GI import generate_gi_parameters_from_df, generate_gi_enzymes_transporters_from_df
from modules.Lung.generate_lung_parameters import generate_lung_parameters_from_df
from modules.Heart.Heart import generate_heart_parameters_from_df
from modules.Brain.generate_brain_parameters import generate_brain_parameters_from_df
from modules.Blood.Blood import generate_blood_parameters_from_df
from modules.Tissue_composition.Tissue_composition import generate_tissue_composition_parameters_from_df, tissue_composition_long_to_wide
from modules.Tissue_Flow_Rates.Tissue_Flow_Rate import generate_tissue_flow_rate_parameters_from_df, tissue_flow_rate_long_to_wide
from pipeline.rename_utils import *

kidney_df = generate_kidney_parameters_from_df(pop_df)
kidney_df = rename_kidney_columns(kidney_df)

# 生成Kidney转运体数据
kidney_transporters_df = generate_kidney_transporters_from_df(pop_df, random_seed=42)

liver_calc = LiverParametersCalculator()
liver_df = liver_calc.process_demographic_data(
    pop_df.rename(columns={'bsa': 'BSA (m2)', 'age': 'Age(years)'}),
    bsa_column='BSA (m2)', age_column='Age(years)', random_seed=42)
liver_df = rename_liver_columns(liver_df)

# 生成肝脏酶和转运体数据
liver_enzymes_df = generate_liver_enzymes_transporters_from_df(pop_df, random_seed=42)

# 生成GI酶和转运体数据
gi_enzymes_df = generate_gi_enzymes_transporters_from_df(pop_df, random_seed=42)

gi_df = generate_gi_parameters_from_df(pop_df)
gi_df = rename_gi_columns(gi_df)

lung_df = generate_lung_parameters_from_df(pop_df)
lung_df = rename_lung_columns(lung_df)

heart_df = generate_heart_parameters_from_df(pop_df)
heart_df = rename_heart_columns(heart_df)

brain_df = generate_brain_parameters_from_df(pop_df)
brain_df = rename_brain_columns(brain_df)

blood_df = generate_blood_parameters_from_df(pop_df)
blood_df = rename_blood_columns(blood_df)

# 合并所有参数，避免重复参数和冗余人口学字段
merge_dfs = [pop_df, kidney_df, kidney_transporters_df, liver_df, liver_enzymes_df, gi_df, gi_enzymes_df, lung_df, heart_df, brain_df, blood_df]
base_cols = ['height', 'weight', 'bsa', 'sex', 'age']
module_prefixes = ['Kidney_', 'Liver_', 'Lung_', 'Heart_', 'Brain_', 'Blood_', 'Tissue_', 'GI_']
used_cols = set(pop_df.columns)
for i in range(1, len(merge_dfs)):
    # 只保留当前模块中未在前面模块出现过的参数（id除外）
    drop_cols = [col for col in merge_dfs[i].columns if col in used_cols and col != 'id']
    # 额外去除所有模块前缀+基础人口学字段名的冗余字段
    for prefix in module_prefixes:
        for base in base_cols:
            drop_cols += [col for col in merge_dfs[i].columns if col.lower() == f'{prefix}{base}'.lower()]
    merge_dfs[i] = merge_dfs[i].drop(columns=list(set(drop_cols)), errors='ignore')
    used_cols.update(merge_dfs[i].columns)

# 生成组织成分参数（长表）
comp_long_df = generate_tissue_composition_parameters_from_df(pop_df)
# 转换为宽表，只保留EW/IW，并输出绝对体积
comp_wide_df = tissue_composition_long_to_wide(comp_long_df, pop_df)

# 生成组织流率参数（长表）
flow_long_df = generate_tissue_flow_rate_parameters_from_df(pop_df)
# 转换为宽表
flow_wide_df = tissue_flow_rate_long_to_wide(flow_long_df)

# 合并所有参数
total_df = merge_dfs[0]
for df in merge_dfs[1:]:
    total_df = pd.merge(total_df, df, on='id', how='left')
# 再合并EW/IW宽表
total_df = pd.merge(total_df, comp_wide_df, on='id', how='left')
# 再合并Tissue Flow Rate宽表
total_df = pd.merge(total_df, flow_wide_df, on='id', how='left')

# 去除重复含义的列，只保留一次
# 以pop_df为主，保留sex、age、height、weight、bsa，去除其它_x/_y/gender等
cols_to_drop = [col for col in total_df.columns if (
    col.endswith('_x') or col.endswith('_y') or col == 'gender') and col not in ['sex', 'age', 'height', 'weight', 'bsa']]
total_df = total_df.drop(columns=cols_to_drop, errors='ignore')

# 新增：去除所有酶/转运体的基因型和表型相关字段（但保留肝脏、GI和Kidney模块的酶和转运体数据）
remove_keywords = ['cyp_', 'genotype', 'phenotype', 'enzyme_', 'transporter_']
genetic_cols = [col for col in total_df.columns if any(kw in col.lower() for kw in remove_keywords) and not (col.startswith('Liver_') or col.startswith('GI_') or col.startswith('Kidney_'))]
total_df = total_df.drop(columns=genetic_cols, errors='ignore')

# 调试：检查肝脏酶数据是否被保留
liver_cyp_cols = [col for col in total_df.columns if col.startswith('Liver_') and 'CYP' in col]
print(f'保留的肝脏CYP列数: {len(liver_cyp_cols)}')
if liver_cyp_cols:
    print('前5个肝脏CYP列:', liver_cyp_cols[:5])

# 调试：检查GI酶和转运体数据是否被保留
gi_cyp_cols = [col for col in total_df.columns if col.startswith('GI_') and 'CYP' in col]
gi_transporter_cols = [col for col in total_df.columns if col.startswith('GI_') and ('ABCB' in col or 'ABCC' in col or 'ABCG' in col or 'SLC' in col or 'SLCO' in col)]
print(f'保留的GI CYP列数: {len(gi_cyp_cols)}')
print(f'保留的GI转运体列数: {len(gi_transporter_cols)}')
if gi_cyp_cols:
    print('前5个GI CYP列:', gi_cyp_cols[:5])
if gi_transporter_cols:
    print('前5个GI转运体列:', gi_transporter_cols[:5])

# 调试：检查Kidney转运体数据是否被保留
kidney_transporter_cols = [col for col in total_df.columns if col.startswith('Kidney_') and ('ABCB' in col or 'ABCC' in col or 'ABCG' in col or 'SLC' in col or 'SLCO' in col)]
print(f'保留的Kidney转运体列数: {len(kidney_transporter_cols)}')
if kidney_transporter_cols:
    print('前5个Kidney转运体列:', kidney_transporter_cols[:5])

# 合并所有参数完成后，显式删除所有模块前缀+人口学主表字段名（包括带括号和空格的）
redundant_patterns = [
    'Liver_Age(years)', 'Liver_BSA (m2)', 'Kidney_gender',
    'Liver_age', 'Liver_bsa', 'Kidney_sex', 'Kidney_age', 'Kidney_bsa',
]
total_df = total_df.drop(columns=[col for col in total_df.columns if col in redundant_patterns], errors='ignore')

# 输出最终结果
# 智能调整人口学字段顺序
pop_cols_candidates = [
    ('sex', ['sex', 'gender']),
    ('age', ['age', 'Age(years)']),
    ('bsa', ['bsa', 'BSA (m2)'])
]
pop_cols = ['id', 'height', 'weight']
for main_name, candidates in pop_cols_candidates:
    for cand in candidates:
        if cand in total_df.columns:
            pop_cols.append(cand)
            break
# 保证主列唯一且顺序正确
pop_cols = [col for col in ['id', 'sex', 'age', 'height', 'weight', 'bsa'] if col in total_df.columns] + [col for col in total_df.columns if col not in ['id', 'sex', 'age', 'height', 'weight', 'bsa']]
total_df = total_df[pop_cols]
total_df.to_csv('total_population_parameters.csv', index=False)

comp_df = generate_tissue_composition_parameters_from_df(total_df)
comp_df = rename_tissue_composition_columns(comp_df)
comp_df.to_csv('tissue_composition_longtable.csv', index=False)

print('全部参数生成、重命名、合并与输出完毕！') 